﻿using System;
using System.ComponentModel;
using System.Windows.Threading;

namespace estoque
{
    public class TimeAccount : INotifyPropertyChanged
    {
        private DispatcherTimer timer;

        public TimeAccount()
        {
            this.Start = DateTime.Now;

            this.UpdateAllTheProperties();

            timer = new DispatcherTimer();
            timer.Interval = new TimeSpan(0, 0, 45);
            timer.Tick += new EventHandler(Timer_Tick);
            timer.Start();
        }

        private DateTime start;

        public DateTime Start
        {
            get { return start; }
            set
            {
                start = value;
                this.UpdateAllTheProperties();
            }
        }

        public TimeSpan DefaultPresenceAmount = new TimeSpan(8, 45, 0);

        public TimeSpan DefaultMaxOvertime = new TimeSpan(2, 0, 0);

        public DateTime End
        {
            get
            {
                return this.Start.Add(this.DefaultPresenceAmount);
            }
        }

        public TimeSpan CurrentPresence
        {
            get
            {
                return DateTime.Now.Subtract(this.Start);
            }
        }

        public TimeSpan MaxPresence
        {
            get
            {
                TimeSpan ts = DefaultPresenceAmount.Add(DefaultMaxOvertime);
                DateTime maxHour = Start.Add(ts);
                TimeSpan retVal = DateTime.Now.Subtract(maxHour);
                return retVal;
            }
        }

        public TimeSpan Overtime
        {
            get
            {
                TimeSpan ts = CurrentPresence.Subtract(DefaultPresenceAmount);
                if (ts.TotalMilliseconds > 0)
                {
                    return ts;
                }
                return new TimeSpan();
            }
        }

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        private void UpdateAllTheProperties()
        {
            PropertyChangedEventHandler temp = this.PropertyChanged;
            if (temp != null)
            {
                temp(this, new PropertyChangedEventArgs("Overtime"));
                temp(this, new PropertyChangedEventArgs("CurrentPresence"));
                temp(this, new PropertyChangedEventArgs("MaxPresence"));
                temp(this, new PropertyChangedEventArgs("End"));
            }
        }

        #endregion INotifyPropertyChanged Members

        private void Timer_Tick(object sender, EventArgs e)
        {
            UpdateAllTheProperties();

            timer.Start();
        }
    }
}